import { ref } from 'vue';
import { useAdminStore } from '@/stores/admin-store';
import { useWebSocketStore } from '@/stores/websocket-store';
import { mixinJE, useJE } from '@common/helper/je';
import { loadDynamicApp, openMicroApp } from '@/hooks/use-micro';
import { openAdminMenu } from '@/hooks/use-menu';

/**
 * 主应用特有方法
 * @returns
 */
function useAdmin() {
  const adminStore = useAdminStore();
  return {
    /**
     * 触发微应用事件
     * @param {*} name
     * @param  {...any} args
     */
    emitMicroEvent(name, ...args) {
      return adminStore.emitMicro(name, ...args);
    },
    /**
     * 是否包含微应用配置
     * @param {*} name
     * @param  {...any} args
     */
    hasMicroConfig(name, ...args) {
      return adminStore.hasMicroConfig(name, ...args);
    },
    /**
     * 打开微应用
     */
    openMicroApp,
    /**
     * 动态加载app
     */
    loadDynamicApp,
    /**
     * 打开菜单
     */
    openMenu: openAdminMenu,
    watchWebSocket,
    useDebugger,
  };
}

/**
 * 触发微应用事件
 * @param {*} name
 * @param  {...any} args
 */
function emitMicroEvent(name, ...args) {
  const adminStore = useAdminStore();
  adminStore.emitMicro(name, ...args);
}
/**
 * 监听websocket消息
 * @param {*} watchFn
 * @returns
 */
const watchWebSocket = (watchFn) => {
  const webSocketStore = useWebSocketStore();
  return webSocketStore.addWatch(watchFn);
};

/**
 * 混入系统方法到JE
 */
export function mixinJE4Admin() {
  const system = useJE().useSystem();

  mixinJE({
    // TODO: 后期会废弃
    useSystem() {
      return { emitMicroEvent, watchWebSocket, ...system };
    },
    useAdmin,
  });
}

/**
 * 启用调试模式
 * @returns
 */
const debug = ref(false);
export function useDebugger() {
  return debug;
}
